<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Refresh, Edit, Delete, Present, Upload } from '@element-plus/icons-vue'
import request from '@/utils/request'

const API_BASE_URL = (import.meta as any)?.env?.VITE_API_BASE_URL || ''

interface Gift {
  id: string
  name: string
  iconUrl?: string
  pricePoints: string
  isActive: boolean
  effectPreset?: string
  effectOptions?: any
  createdAt: string
  updatedAt: string
}

const giftList = ref<Gift[]>([])
const giftForm = reactive({
  name: '',
  iconUrl: '',
  pricePoints: 0,
  isActive: true,
  effectPreset: 'burst' as 'burst' | 'fireworks' | 'side' | 'pride'
})
const giftDialog = ref(false)
const editingId = ref<string | null>(null)
const loading = ref(false)
const uploadingIcon = ref(false)

// 特效预设选项
const effectPresets = [
  { label: '기본 폭발', value: 'burst' },
  { label: '불꽃놀이', value: 'fireworks' },
  { label: '양쪽 폭발', value: 'side' },
  { label: '프라이드', value: 'pride' }
]

async function fetchGifts() {
  loading.value = true
  try {
    const { data } = await request.get('/api/admin/gifts')
    giftList.value = data
  } catch (error) {
    ElMessage.error('선물 목록 가져오기 실패')
  } finally {
    loading.value = false
  }
}

function resetForm() {
  giftForm.name = ''
  giftForm.iconUrl = ''
  giftForm.pricePoints = 0
  giftForm.isActive = true
  giftForm.effectPreset = 'burst'
  editingId.value = null
}

function openCreateDialog() {
  resetForm()
  giftDialog.value = true
}

function openEditDialog(row: Gift) {
  giftForm.name = row.name
  giftForm.iconUrl = row.iconUrl || ''
  giftForm.pricePoints = Number(row.pricePoints)
  giftForm.isActive = row.isActive
  giftForm.effectPreset = (row.effectPreset as any) || 'burst'
  editingId.value = row.id
  giftDialog.value = true
}

async function saveGift() {
  if (!giftForm.name || !giftForm.pricePoints) {
    ElMessage.error('이름과 가격을 입력하세요')
    return
  }

  try {
    if (editingId.value) {
      // 편집
      await request.put(`/api/admin/gifts/${editingId.value}`, giftForm)
      ElMessage.success('업데이트 성공')
    } else {
      // 신규 추가
      await request.post('/api/admin/gifts', giftForm)
      ElMessage.success('생성 성공')
    }
    giftDialog.value = false
    await fetchGifts()
  } catch (error) {
    ElMessage.error(editingId.value ? '업데이트 실패' : '생성 실패')
  }
}

async function toggleGift(row: Gift) {
  try {
    await request.put(`/api/admin/gifts/${row.id}`, { isActive: !row.isActive })
    ElMessage.success('상태 업데이트 성공')
    await fetchGifts()
  } catch (error) {
    ElMessage.error('상태 업데이트 실패')
  }
}

async function deleteGift(row: Gift) {
  try {
    await ElMessageBox.confirm('이 선물을 삭제하시겠습니까?', '삭제 확인', {
      confirmButtonText: '확인',
      cancelButtonText: '취소',
      type: 'warning',
    })

    await request.delete(`/api/admin/gifts/${row.id}`)
    ElMessage.success('삭제 성공')
    await fetchGifts()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('삭제 실패')
    }
  }
}

// 선물 아이콘 업로드
async function uploadGiftIcon(file: File) {
  if (!file.type.startsWith('image/')) {
    ElMessage.error('이미지 파일을 선택하세요')
    return false
  }

  if (file.size > 5 * 1024 * 1024) {
    ElMessage.error('이미지 크기는 5MB를 초과할 수 없습니다')
    return false
  }

  uploadingIcon.value = true
  try {
    const formData = new FormData()
    formData.append('icon', file)

    const response = await request.post('/api/admin/uploads/gift-icon', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })

    giftForm.iconUrl = response.data.iconUrl
    ElMessage.success('아이콘 업로드 성공')
    return true
  } catch (error: any) {
    ElMessage.error(error.response?.data?.error || '아이콘 업로드 실패')
    return false
  } finally {
    uploadingIcon.value = false
  }
}

function formatPoints(points: string | number) {
  return Number(points).toLocaleString()
}

function getImageUrl(url: string) {
  if (!url) return ''
  if (url.startsWith('http://') || url.startsWith('https://')) {
    return url
  }
  return `${API_BASE_URL}${url}`
}

function getEffectLabel(preset: string) {
  const effect = effectPresets.find(e => e.value === preset)
  return effect?.label || '기본 폭발'
}

onMounted(() => {
  fetchGifts()
})
</script>


<template>
  <div class="gift-management">
    <!-- 页面标题 -->
    <div class="page-header">
      <div class="header-content">
        <el-icon class="page-icon" size="24">
          <Present />
        </el-icon>
        <div class="header-text">
          <h1 class="page-title">선물 관리</h1>
          <p class="page-subtitle">가상 선물을 관리합니다</p>
        </div>
      </div>
    </div>

    <!-- 工具栏 -->
    <div class="toolbar">
      <el-button type="primary" :icon="Plus" @click="openCreateDialog" size="small">
        선물 추가
      </el-button>
      <el-button :icon="Refresh" @click="fetchGifts" size="small">
        새로고침
      </el-button>
    </div>

    <!-- 선물 목록 -->
    <div v-loading="loading" class="gift-list">
      <div v-if="giftList.length === 0" class="empty-state">
        <el-empty description="등록된 선물이 없습니다" />
      </div>
      <div v-else class="gift-cards">
        <div v-for="gift in giftList" :key="gift.id" class="gift-card">
          <div class="card-header">
            <div class="card-title-section">
              <div class="card-title">{{ gift.name }}</div>
              <div class="card-badges">
                <el-tag :type="gift.isActive ? 'success' : 'info'" size="small">
                  {{ gift.isActive ? '판매 중' : '판매 중지' }}
                </el-tag>
                <el-tag v-if="gift.effectPreset" size="small" type="warning">
                  {{ getEffectLabel(gift.effectPreset) }}
                </el-tag>
              </div>
            </div>
            <div class="card-actions">
              <el-button
                type="primary"
                :icon="Edit"
                @click="openEditDialog(gift)"
                size="small"
                text
              />
              <el-button
                type="danger"
                :icon="Delete"
                @click="deleteGift(gift)"
                size="small"
                text
              />
            </div>
          </div>

          <div class="card-content">
            <div class="gift-icon-section">
              <img
                v-if="gift.iconUrl"
                :src="getImageUrl(gift.iconUrl)"
                :alt="gift.name"
                class="gift-icon"
              />
              <div v-else class="no-icon">
                <el-icon size="32"><Present /></el-icon>
                <span>아이콘 없음</span>
              </div>
            </div>

            <div class="gift-info">
              <div class="info-row">
                <span class="label">가격:</span>
                <span class="value price">{{ formatPoints(gift.pricePoints) }} 포인트</span>
              </div>
              <div class="info-row">
                <span class="label">특수 효과:</span>
                <span class="value">{{ getEffectLabel(gift.effectPreset || 'burst') }}</span>
              </div>
              <div class="info-row">
                <span class="label">등록일:</span>
                <span class="value">{{ new Date(gift.createdAt).toLocaleDateString() }}</span>
              </div>
            </div>
          </div>

          <div class="card-footer">
            <el-button
              :type="gift.isActive ? 'warning' : 'success'"
              @click="toggleGift(gift)"
              size="small"
            >
              {{ gift.isActive ? '판매 중지' : '판매 시작' }}
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="giftDialog"
      :title="editingId ? '선물 편집' : '선물 추가'"
      width="90%"
      class="mobile-dialog"
    >
      <el-form :model="giftForm" label-position="top" class="mobile-form">
        <el-form-item label="선물 이름" required>
          <el-input v-model="giftForm.name" placeholder="선물 이름을 입력하세요" />
        </el-form-item>

        <el-form-item label="가격 (포인트)" required>
          <el-input-number
            v-model="giftForm.pricePoints"
            :min="1"
            class="full-width"
            controls-position="right"
          />
        </el-form-item>

        <el-form-item label="특수 효과">
          <el-select v-model="giftForm.effectPreset" class="full-width">
            <el-option
              v-for="effect in effectPresets"
              :key="effect.value"
              :label="effect.label"
              :value="effect.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="선물 아이콘">
          <div class="icon-upload-section">
            <div class="icon-preview">
              <img
                v-if="giftForm.iconUrl"
                :src="getImageUrl(giftForm.iconUrl)"
                :alt="giftForm.name"
                class="preview-icon"
              />
              <div v-else class="no-preview">
                <el-icon size="32"><Present /></el-icon>
                <span>아이콘 없음</span>
              </div>
            </div>
            <div class="icon-controls">
              <el-upload
                :action="`${API_BASE_URL}/api/admin/uploads/gift-icon`"
                name="icon"
                :with-credentials="true"
                :show-file-list="false"
                :before-upload="uploadGiftIcon"
                :loading="uploadingIcon"
                class="upload-button"
              >
                <el-button type="primary" size="small" :loading="uploadingIcon">
                  아이콘 업로드
                </el-button>
              </el-upload>
              <el-input
                v-model="giftForm.iconUrl"
                placeholder="또는 아이콘 URL 직접 입력"
                size="small"
              />
            </div>
          </div>
        </el-form-item>

        <el-form-item label="설정">
          <div class="switch-group">
            <div class="switch-item">
              <el-switch v-model="giftForm.isActive" />
              <span class="switch-label">판매 활성화</span>
            </div>
          </div>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="giftDialog = false">취소</el-button>
          <el-button type="primary" @click="saveGift">저장</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.gift-management {
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 16px;
  background-color: #f5f5f5;
}

/* 页面标题 */
.page-header {
  margin-bottom: 20px;
}

.header-content {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 16px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.page-icon {
  color: var(--el-color-primary);
}

.header-text {
  flex: 1;
}

.page-title {
  font-size: 18px;
  font-weight: 600;
  color: var(--el-text-color-primary);
  margin: 0 0 4px 0;
}

.page-subtitle {
  font-size: 14px;
  color: var(--el-text-color-regular);
  margin: 0;
}

/* 工具栏 */
.toolbar {
  display: flex;
  gap: 8px;
  margin-bottom: 16px;
}

.toolbar .el-button {
  flex: 1;
}

/* 선물 목록 */
.gift-list {
  flex: 1;
  overflow-y: auto;
}

.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
  background: white;
  border-radius: 8px;
}

.gift-cards {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

/* 선물 카드 */
.gift-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  padding: 16px;
  background: #fafafa;
  border-bottom: 1px solid var(--el-border-color-lighter);
}

.card-title-section {
  flex: 1;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
  color: var(--el-text-color-primary);
  margin-bottom: 8px;
}

.card-badges {
  display: flex;
  gap: 4px;
  flex-wrap: wrap;
}

.card-actions {
  display: flex;
  gap: 4px;
}

.card-content {
  display: flex;
  padding: 16px;
  gap: 16px;
}

.gift-icon-section {
  flex-shrink: 0;
  width: 80px;
  height: 80px;
}

.gift-icon {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 6px;
}

.no-icon {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: #f5f5f5;
  border-radius: 6px;
  color: var(--el-text-color-placeholder);
  font-size: 12px;
}

.gift-info {
  flex: 1;
}

.info-row {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 8px;
}

.info-row:last-child {
  margin-bottom: 0;
}

.info-row .label {
  font-size: 14px;
  color: var(--el-text-color-regular);
  min-width: 80px;
}

.info-row .value {
  font-size: 14px;
  color: var(--el-text-color-primary);
  text-align: right;
  flex: 1;
}

.info-row .value.price {
  font-weight: 600;
  color: var(--el-color-warning);
}

.card-footer {
  display: flex;
  gap: 8px;
  padding: 12px 16px;
  background: #fafafa;
  border-top: 1px solid var(--el-border-color-lighter);
}

.card-footer .el-button {
  flex: 1;
}

/* 对话框样式 */
.mobile-dialog {
  margin: 5vh auto;
}

.mobile-dialog :deep(.el-dialog) {
  border-radius: 8px;
}

.mobile-dialog :deep(.el-dialog__header) {
  padding: 16px 20px 12px;
}

.mobile-dialog :deep(.el-dialog__body) {
  padding: 0 20px 16px;
  max-height: 70vh;
  overflow-y: auto;
}

.mobile-form {
  padding: 0;
}

.mobile-form .el-form-item {
  margin-bottom: 20px;
}

.mobile-form :deep(.el-form-item__label) {
  font-size: 14px;
  font-weight: 500;
  margin-bottom: 8px;
}

.full-width {
  width: 100%;
}

/* 아이콘 업로드 구역 */
.icon-upload-section {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.icon-preview {
  align-self: center;
  width: 80px;
  height: 80px;
}

.preview-icon {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 6px;
  border: 1px solid var(--el-border-color-light);
}

.no-preview {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: #f5f5f5;
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  color: var(--el-text-color-placeholder);
  font-size: 12px;
}

.icon-controls {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.upload-button {
  align-self: center;
}

/* 开关组 */
.switch-group {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.switch-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.switch-label {
  font-size: 14px;
  color: var(--el-text-color-primary);
}

.dialog-footer {
  display: flex;
  gap: 12px;
}

.dialog-footer .el-button {
  flex: 1;
}

/* 响应式适配 */
@media (max-width: 480px) {
  .gift-management {
    padding: 12px;
  }

  .header-content {
    padding: 12px;
  }

  .page-title {
    font-size: 16px;
  }

  .card-content {
    padding: 12px;
    gap: 12px;
  }

  .gift-icon-section {
    width: 60px;
    height: 60px;
  }

  .mobile-dialog {
    width: 95% !important;
    margin: 2vh auto;
  }

  .icon-preview {
    width: 60px;
    height: 60px;
  }
}

/* 暗黑模式适配 */
:root.dark .gift-card {
  background: var(--el-bg-color);
  border-color: var(--el-border-color);
}
</style>
